package com.yugao.fintech.antelope.codegen.core;

import com.yugao.fintech.antelope.codegen.core.document.DefaultDocumentTableHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
public class DocumentTableFactory {
    private static final Map<DbType, DocumentTableHandler> tableDialectHandlerMap = new ConcurrentHashMap<>();
    private static final DefaultDocumentTableHandler defaultDocumentTableHandler = new DefaultDocumentTableHandler();
    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        applicationContext.getBeansOfType(DocumentTableHandler.class)
                .forEach((k, v) -> tableDialectHandlerMap.put(v.dbType(), v));
    }

    public static DocumentTableHandler build(GeneratorConfig generatorConfig) {
        Integer dbType = generatorConfig.getDbType();
        DocumentTableHandler documentTableHandler = tableDialectHandlerMap.get(DbType.of(dbType));
        if (documentTableHandler == null) {
            return defaultDocumentTableHandler;
        } else {
            return documentTableHandler;
        }
    }
}
